{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-02T06:16:28.169730Z",
     "start_time": "2018-09-02T06:16:25.203029Z"
    }
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import random as rn\n",
    "\n",
    "import os\n",
    "os.environ['PYTHONHASHSEED'] = '0'\n",
    "np.random.seed(42)\n",
    "rn.seed(12345)\n",
    "session_conf = tf.ConfigProto(device_count={\"CPU\": 4},intra_op_parallelism_threads=1, inter_op_parallelism_threads=1)\n",
    "\n",
    "from keras import backend as K\n",
    "\n",
    "\n",
    "tf.set_random_seed(1234)\n",
    "sess = tf.Session(graph=tf.get_default_graph(), config=session_conf)\n",
    "K.set_session(sess)\n",
    "\n",
    "\n",
    "\n",
    "import pandas as pd\n",
    "\n",
    "import pickle\n",
    "from sklearn.model_selection import PredefinedSplit\n",
    "\n",
    "from keras.models import Sequential\n",
    "from keras.layers.core import Dense, Dropout, Activation\n",
    "\n",
    "from keras.layers.normalization import BatchNormalization\n",
    "from keras.optimizers import Adam\n",
    "from keras.callbacks import EarlyStopping\n",
    "from keras import regularizers\n",
    "from keras import initializers\n",
    "from sklearn.metrics import mean_squared_error\n",
    "Path = 'D:\\\\APViaML'\n",
    "from keras.callbacks import ModelCheckpoint\n",
    "from keras.models import load_model\n",
    "\n",
    "from hyperopt import fmin, tpe, hp, STATUS_OK, Trials\n",
    "pd.set_option('display.max_columns', 50)\n",
    "pd.set_option('display.max_rows', 100)\n",
    "pd.set_option('display.float_format', lambda x: '%.3f' % x)\n",
    "\n",
    "\n",
    "def get_demo_dict_data():\n",
    "    file = open(Path + '\\\\data\\\\alldata_demo_top1000.pkl','rb')\n",
    "    raw_data = pickle.load(file)\n",
    "    file.close()\n",
    "    return raw_data\n",
    "\n",
    "data = get_demo_dict_data()\n",
    "\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']\n",
    "\n",
    "def creat_data(num,df_X=top_1000_data_X,df_Y=top_1000_data_Y):\n",
    "    '''\n",
    "    Data providing function:\n",
    "\n",
    "    This function is separated from model() so that hyperopt\n",
    "    won't reload data for each evaluation run.\n",
    "    '''\n",
    "    traindata_startyear_str = str(1958) \n",
    "    traindata_endyear_str = str(num + 1987) \n",
    "    vdata_startyear_str = str(num + 1976) \n",
    "    vdata_endyear_str = str(num + 1987) \n",
    "    testdata_startyear_str = str(num + 1988) \n",
    "  \n",
    "    X_traindata =  np.array(df_X.loc[traindata_startyear_str:traindata_endyear_str])\n",
    "    Y_traindata = np.array(df_Y.loc[traindata_startyear_str:traindata_endyear_str])\n",
    "    X_vdata = np.array(df_X.loc[vdata_startyear_str:vdata_endyear_str])\n",
    "    Y_vdata = np.array(df_Y.loc[vdata_startyear_str:vdata_endyear_str])\n",
    "    X_testdata = np.array(df_X.loc[testdata_startyear_str])\n",
    "    Y_testdata = np.array(df_Y.loc[testdata_startyear_str])\n",
    "        \n",
    "    return X_traindata, Y_traindata, X_vdata, Y_vdata, X_testdata, Y_testdata\n",
    "\n",
    "\n",
    "def Evaluation_fun(predict_array,real_array):\n",
    "    List1 = []\n",
    "    List2 = []\n",
    "    if len(predict_array) != len(real_array):\n",
    "        print('Something is worng!')\n",
    "    else:\n",
    "        for i in range(len(predict_array)):\n",
    "            List1.append(np.square(predict_array[i]-real_array[i]))\n",
    "            List2.append(np.square(real_array[i]))\n",
    "        result = round(100*(1 - sum(List1)/sum(List2)),3)\n",
    "    return result\n",
    "\n",
    "\n",
    "data = get_demo_dict_data()\n",
    "\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']\n",
    "del data\n",
    "\n",
    "\n",
    "\n",
    "def creat_test_data(num,df_X=top_1000_data_X,df_Y=top_1000_data_Y):\n",
    "    \n",
    "    testdata_startyear_str = str(num + 1988) \n",
    "    X_testdata = np.array(df_X.loc[testdata_startyear_str])\n",
    "    Y_testdata = np.array(df_Y.loc[testdata_startyear_str])\n",
    "    return X_testdata, Y_testdata\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-02T13:14:54.958948Z",
     "start_time": "2018-09-02T12:59:38.128064Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "7\n",
      "8\n",
      "9\n",
      "10\n",
      "11\n",
      "12\n",
      "13\n",
      "14\n",
      "15\n",
      "16\n",
      "17\n",
      "18\n",
      "19\n",
      "20\n",
      "21\n",
      "22\n",
      "23\n",
      "24\n",
      "25\n",
      "26\n",
      "27\n",
      "28\n",
      "29\n"
     ]
    }
   ],
   "source": [
    "Y_pre_list_final= []\n",
    "test_performance_score_list = []\n",
    "for i in range(30):\n",
    "    print(i)\n",
    "    X_testdata, Y_testdata = creat_test_data(num=i)\n",
    "    model_filepath = Path + '\\\\model\\\\NN1\\\\'+ str(i+1988)+'_Model_NN1_Top1000_Prediction.h5'\n",
    "    best_model = load_model(model_filepath)\n",
    "    Y_pre =best_model.predict(X_testdata,verbose = 0)\n",
    "    Y_pre_list=[]\n",
    "    for x in Y_pre[:,0]:\n",
    "        Y_pre_list.append(x)\n",
    "    test_score = Evaluation_fun(Y_pre_list, Y_testdata)\n",
    "    Y_pre_list_final.append(Y_pre_list)\n",
    "    test_performance_score_list.append(test_score)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-02T13:14:56.247341Z",
     "start_time": "2018-09-02T13:14:55.708422Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Performance by Average: 0.34186666666666665\n"
     ]
    }
   ],
   "source": [
    "data = get_demo_dict_data()\n",
    "\n",
    "top_1000_data_X = data['X']\n",
    "top_1000_data_Y = data['Y']\n",
    "del data\n",
    "print('Model Performance by Average:',np.mean(test_performance_score_list))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-02T13:14:57.075523Z",
     "start_time": "2018-09-02T13:14:57.051961Z"
    }
   },
   "outputs": [],
   "source": [
    "Y_pre_list=[]\n",
    "for i in  range(30):\n",
    "    temp_list = Y_pre_list_final[i]\n",
    "    Y_pre_list =Y_pre_list+temp_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-02T13:14:58.278692Z",
     "start_time": "2018-09-02T13:14:57.894181Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model Performance: 0.859\n"
     ]
    }
   ],
   "source": [
    "y_real = np.array(top_1000_data_Y.loc['1988':])\n",
    "print('Model Performance:',Evaluation_fun(Y_pre_list, y_real))\n",
    "\n",
    "file = open(Path + '\\\\output\\\\data\\\\Model_NN1_Top1000_Prediction.pkl', 'wb')\n",
    "pickle.dump(Y_pre_list, file)\n",
    "file.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2018-09-02T13:14:59.100858Z",
     "start_time": "2018-09-02T13:14:59.091333Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[15.068,\n",
       " 15.892,\n",
       " -29.408,\n",
       " 10.648,\n",
       " 8.143,\n",
       " 9.269,\n",
       " -23.741,\n",
       " 18.954,\n",
       " 15.123,\n",
       " 21.647,\n",
       " -0.601,\n",
       " 2.26,\n",
       " -10.859,\n",
       " -36.035,\n",
       " -11.084,\n",
       " 2.721,\n",
       " 19.086,\n",
       " 8.637,\n",
       " 15.604,\n",
       " 0.128,\n",
       " -43.992,\n",
       " -6.326,\n",
       " 14.014,\n",
       " -19.6,\n",
       " 0.267,\n",
       " 22.591,\n",
       " 5.127,\n",
       " -35.232,\n",
       " 1.814,\n",
       " 20.141]"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_performance_score_list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.6"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "position": {
    "height": "624px",
    "left": "1258px",
    "right": "20px",
    "top": "123px",
    "width": "593px"
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
